<?php

namespace app\admin\controller\cost;

use app\common\controller\Backend;
use app\common\model\Hospital;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 成本管理
 *
 * @icon fa fa-circle-o
 */
class Cost extends Backend
{

    /**
     * Cost模型对象
     * @var \app\common\model\cost\Cost
     */
    protected $model = null;
    protected $searchFields = 'warranty.workID,warranty.product,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\cost\Cost;
        $this->view->assign("billingDataList", $this->model->getBillingDataList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['warranty','category','user'])
                    ->field("a.name 'a.name',a.marking 'a.marking'")
                    ->join("equipment a","a.id=warranty.equipment_id",'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('warranty')->visible(['product','device','workID']);
				$row->getRelation('category')->visible(['name']);
				$row->getRelation('user')->visible(['nickname','avatar']);
            }
            $money = $this->model
                ->with(['warranty','category','user'])
                ->field("a.name 'a.name',a.marking 'a.marking'")
                ->join("equipment a","a.id=warranty.equipment_id",'left')
                ->where($where)
                ->sum("cost.money");
            $result = array("total" => $list->total(), "rows" => $list->items(),'money'=>$money);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     * */
    public function see($ids){
        $row=$this->model
            ->with(['warranty'=>function($query){
                $query->withField('id,product,device,workID');
            },'category'=>function($query){
                $query->withField('id,name');
            },'user'=>function($query){
                $query->withField('id,nickname,avatar');
            }])
            ->field("a.name equipment_name,a.marking equipment_marking")
            ->join("equipment a","a.id=warranty.equipment_id",'left')
            ->find(["cost.id"=>$ids]);
        if (!empty($row["billing_images"])) $row["billing_images"]=explode(",",$row["billing_images"]);
        if (!empty($row["images"])) $row["images"]=explode(",",$row["images"]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
    * 审核
    * */
    public function operation(){
        if (!$this->request->param("ids")) $this->error('id为空');
        $param=$this->request->param();
        $row = $this->model->get($param["ids"]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $result = $row->allowField(true)->save($param);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    /*
     * 导出
     * */
    public function export()
    {
        if ($this->request->isPost()) {
            //当前是否为关联查询
            $this->relationSearch = true;
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $filter = (array)json_decode($filter, true);
            $op = $this->request->post('op');
            //$excel = new PHPExcel();
            $spreadsheet = new Spreadsheet();

            $spreadsheet->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);
            $whereIds = $ids == 'all' ? '1=1' : ['cost.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => json_encode($filter), 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $line = 1;
            //设置过滤方法
            $this->request->filter(['strip_tags']);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['warranty','category','user'])
                ->field("a.name 'a.name',a.marking 'a.marking'")
                ->join("equipment a","a.id=warranty.equipment_id",'left')
                ->where($where)
                ->where($whereIds)
                ->count();
            $list = $this->model
                ->with(['warranty' => function ($query) {
                    $query->withField('id,workID,hospital_id');
                },'category' => function ($query) {
                    $query->withField('id,name');
                },'user' => function ($query) {
                    $query->withField('id,nickname');
                },])
                ->field("a.name 'a.name',a.marking 'a.marking',a.serial 'a.serial'")
                ->join("equipment a","a.id=warranty.equipment_id",'left')
                ->where($where)
                ->where($whereIds)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            //$title = ['工单ID', '医院名称', '设备名称', '型号', '序列号', '工程师', '销售', '成交价','状态','是否开票','创建时间','成本价','质保到期时间','利润','回款金额','应收账款','收款状态'];
            $filter = $this->request->post('filter');
            $filter = (array)json_decode($filter, true);
            if(array_key_exists("status", $filter) && $filter["status"]==1){
                //保内
                $title = ['工单ID', '医院名称', '设备名称', '型号', '序列号', '有无发票', '报销金额', '创建时间','报销类目','昵称','成本说明'];
            }
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // 方法一，使用 setCellValueByColumnAndRow
            //表头
            //设置单元格内容
            foreach ($title as $key => $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
            }

            $newdata=[];
            foreach ($list as $k=>$v){
                $hospital=Hospital::field("name")->where(["id"=>$v["warranty"]["hospital_id"]])->find();
                $newdata[$k]=[
                    "workID"=>$v["warranty"]["workID"],
                    "hospital.name"=>$hospital["name"]??'',
                    "equipment.name"=>$v["a.name"]??'',
                    "equipment.marking"=>$v["a.marking"]??'',
                    "equipment.serial"=>$v["a.serial"]??'',
                    "billing_data"=>$v["billing_data_text"]??'',
                    "money"=>$v["money"]??0,
                    "createtime"=>date('Y-m-d H:i:s',$v["createtime"])?? '',
                    "category.name"=>$v["category"]["name"]??'',
                    "user.nickname"=>$v["user"]["nickname"]?? '',
                    "explain"=>$v["explain"]?? '',
                ];
            }
            $row = 2; // 从第二行开始
            foreach ($newdata as $item) {
                $column = 1;
                foreach ($item as $k=>$value) {
                    $sheet->setCellValueByColumnAndRow($column, $row, $value);
                    $column++;
                }
                $row++;
            }
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename=' . date('Y-m-d') .'_test'. '.xlsx');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0

            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');

            die();

            $first = array_keys($list[0]);
            foreach ($first as $index => $item) {
                $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
            }
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(ROOT_PATH . 'public/assets/muban.xlsx');  //读取模板
            $worksheet = $spreadsheet->getActiveSheet();     //指向激活的工作表
            $worksheet->setTitle('模板测试标题');
            for($i=0;$i<$total;++$i){
                //向模板表中写入数据
                $i++;
                $columns='workID,hospital.name,equipment.name,equipment.marking,equipment.serial,sale.nickname,engineer.nickname,final_price';
                $worksheet->getCell('A'.$i)->setValue($result['rows'][$i]['workID']);    //星期
                $worksheet->getCell('B'.$i)->setValue($result['rows'][$i]['hospital']["name"]);    //星期
                $worksheet->getCell('C'.$i)->setValue($result['rows'][$i]['equipment']["name"]);  //性别
                $worksheet->getCell('D'.$i)->setValue($result['rows'][$i]['equipment']["marking"]);  //爱好
                $worksheet->getCell('E'.$i)->setValue($result['rows'][$i]['equipment']["serial"]);  //标题
                $worksheet->getCell('F'.$i)->setValue($result['rows'][$i]['sale']["nickname"]);  //内容
                $worksheet->getCell('G'.$i)->setValue($result['rows'][$i]['engineer']["nickname"]);  //内容
                $worksheet->getCell('H'.$i)->setValue($result['rows'][$i]['final_price']);  //内容
                //$worksheet->getCell('I'.$i)->setValue($result['rows'][$i]['final_price']);  //内容
                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
                //下载文档
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'. date('Y-m-d') .'_test'.'.xlsx"');
                header('Cache-Control: max-age=0');
                $writer->save('php://output');

            }
            return;
        }
    }
}
